package org.company.tool.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.Version;

public class FreemarkerUtil {
    
    private static FreemarkerUtil instance = null;
    
    private Configuration cfg = null;
    
    private FreemarkerUtil() {
        cfg = new Configuration();
        try {
            File basePath = new File(ClassLoader.getSystemResource("founder").getPath());
            cfg.setDirectoryForTemplateLoading(basePath);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
        
        cfg.setIncompatibleImprovements(new Version(2, 3, 20));
    }
    
    public static FreemarkerUtil getInstance() {
        if(instance == null)
            instance = new FreemarkerUtil();
        return instance;
    }
    
    public Template getTemplate(String fmp) throws IOException {
        return cfg.getTemplate(fmp);
    }
    
    @SuppressWarnings("rawtypes")
    public void mergeTemplate(String fmp,String targetUri,Map root) throws IOException, TemplateException {
        File file = new File(targetUri);
        if(!file.exists()) {
            new File(file.getParent()).mkdirs();
        }
        Writer writer = new BufferedWriter(new FileWriter(file));
        this.mergeTemplate(fmp, writer, root);
    }
    
    @SuppressWarnings("rawtypes")
    public void mergeTemplate(String fmp,Writer writer,Map root) throws TemplateException, IOException {
        Template template = instance.getTemplate(fmp);
        template.process(root, writer);
    }
}
